<template>
  <div>
    <div>
      <el-row>
        <div style="float: right; margin-right: 50px">
          <el-switch style="margin-right: 20px" @change="switchChange" v-model="value1" active-text="" inactive-text="热点编辑"> </el-switch>
          <!-- <el-button align="center" plain :type="tn" size="mini" @click="startBiaoZhu()">新增</el-button> -->
          <!-- <el-button align="center" plain :type="ty" size="mini" @click="tuoBiaoZhu()">移动</el-button> -->
          <!-- <el-button align="center" plain  size="mini" @click="delBiaoZhu()">删除</el-button> -->
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="delBiaoZhu()" circle></el-button>
          <!-- <el-button align="center" plain  size="mini" @click="chongBiaoZhu()">重置</el-button> -->
        </div>
      </el-row>

      <el-row style="margin-top: 20px">
        <el-col :span="9">
          <!--  <el-table
            fix
            border
            :default-sort = "{prop: 'date', order: 'descending'}"
            id="singleTable"
            ref="singleTable"
            :data="tableInfo"
            style="width: 100%;border: #A8BBC9;"
            size="small"
            v-show="true"
            element-loading-text="正在查询中。。。"
            highlight-current-row
            @current-change="showBiaoZhu"
            :header-cell-style="{'text-align':'center'}">
              <el-table-column sortable align="center" width="70"  prop="redianCode" label="编号"/>
              <el-table-column sortable align="center" width="100" prop="graphicName" label="配件"/>
              <el-table-column sortable align="center" width="70" prop="unitAmount" label="用量"/>
            </el-table> -->

          <FilterTable
            :onSyncTableData="tableList"
            ref="hotsTable"
            :columns="columns"
            :fetchapi="fetchApi"
            :params="fetchParams"
            height="auto"
            :datakey="'records'"
            :onRowSelectChange="selectChange"
            :isToperInfo="false"
            :isSelectColumn="true"
            :dataSource="dataSource"
            :defaultSelections="selectedRow"
            selectionType="single"
            :isPagination="false"
            :isColumnFilter="false"
            :onColumnsChange="(columns) => (this.columns = columns)"
          >
          </FilterTable>
        </el-col>
        <el-col :span="15">
          <div style="width: 600px; height: 500px; position: relative; border: 1px #36c6d3; margin: auto" id="myBiaoZhuDiv">
            <img id="myBiaoZhu" :src="pics" alt="" />
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="dialogBottmView">
      <el-button @click="close">取消</el-button>
      <el-button :loading="loading2" type="primary" @click="subImport">保存</el-button>
    </div>
  </div>
</template>

<script>
import { insertAndUpdate, queryGradeInFo, queryPartsInFo } from '@/api/graphic/hotspotEdit/index.js';
import { getFileGroup } from '@/api/graphic/hotspotEdit/index.js';
import config from '@/assets/js/config';
import axios from '@/api/fetch';
export default {
  name: 'HotspotUpdate',
  components: {},
  props: {
    assemblyId: {
      type: Number,
    },
    graphicCode: {
      type: String,
      default: '2',
    },
    graphicId: {
      type: Number,
    },
  },
  data() {
    return {
      value1: false,
      tableInfo: [],
      fetchApi: queryPartsInFo,
      fetchParams: { xhrAbort: true },
      columns: this.createTableColumns(),
      loading2: false,
      // pics: 'http://117.41.165.126:8085/img/news/part_1655732382455.png',
      pics: '',
      tn: '',
      ty: '',
      selectedRow: [], //选中的行
      addId: '', //新增标号时要用到的id
      delId: undefined, //要删除的标号
      newTab: false, //是否新增标号
      dragging: false, //是否选择拖动
      currentRow: null, //记录当前行
      tableData: [],
      uploadPrefix: config.uploadUrl, // 附件上传前缀
      fixedWidth: undefined,
      fixedHeight: undefined,
      pointSize: 15, //点的大小
      usage: undefined, //记录热点用量
      banMa: [],
    };
  },
  created() {
    console.log(this.graphicCode, '代码');
    let params = Object.assign({}, { graphicCode: this.graphicCode,graphicId:this.graphicId}, { xhrAbort: false });
    this.fetchParams = params;
  },

  mounted() {
    this.init();
    this.getList();
    console.log('开始创建');
    console.log(this.tableData, '开始创建');
    document.getElementById('myBiaoZhu').oncontextmenu = (e) => {
      if (e && e.preventDefault) {
        //阻止默认浏览器动作(W3C)
        e.preventDefault();
      } else {
        //IE中阻止函数器默认动作的方式
        window.event.returnValue = false;
      }
      return false;
    }; //阻止冒泡行为和默认右键菜单事件
    document.getElementById('myBiaoZhu').onmousedown = (e) => {
      e = e || window.event;
      this.myBiaoZhuMousedown(e);
    };
  },
  methods: {
    async init() {
      await getFileGroup({ xtdjid: this.assemblyId, xtfjlx: 'tt_graphic_assembly_info' }).then((response) => {
        if (response.data.length > 0) {
          this.getPicUrl(response.data[0].url).then((res) => {
            this.pics = res;
            let img = document.getElementById('myBiaoZhu');
            let Timg = new Image();
            Timg.src = this.pics;
            Timg.onload = () => {
              // 为什么要写 onload  是因为要等他加载完之后才能获取到图片宽高
              console.log(Timg.width, Timg.height, '宽和高');
              //设置图片初始高度
              this.fixedHeight = Timg.height;
              if (this.fixedHeight > 600) {
                this.fixedHeight = 600;
              }
              img.height = this.fixedHeight;
              //设置图片初始宽度
              this.fixedWidth = img.width;
              //重新设置盒子的大小
              let myBiaoZhuDiv = document.getElementById('myBiaoZhuDiv');
              myBiaoZhuDiv.style.width = img.width + 'px';
              myBiaoZhuDiv.style.height = img.height + 'px';

              // this.fixedWidth=Timg.width;
              // if(this.fixedWidth>600){
              //    this.fixedWidth=600;
              //  }
              // img.width=this.fixedWidth;
            };
          });
        }
      });
    },

    //点击开关触发的方法
    switchChange(val) {
      console.log(val, '开关的值');
      let div = document.getElementById('myBiaoZhuDiv');
      if (this.addId == '') {
        this.value1 = false;
        this.$message.error('请先选择配件!');
        return;
      }
      this.newTab = !this.newTab;
      if (val) {
        div.style.cursor = 'crosshair';
      } else {
        div.style.cursor = '';
      }
    },

    async getPicUrl(url) {
      let actionUrl = this.uploadPrefix + '/api/file/download/url?fileUrl=' + url;
      let res = await axios.post(actionUrl);
      return res.data;
    },

    createTableColumns() {
      return [
        {
          title: '编号',
          dataIndex: 'redianCode',
          align: 'center',
          width: 60,
          sorter: true,
        },
        {
          title: '代码',
          dataIndex: 'graphicCode',
          align: 'center',
          sorter: true,
        },
        {
          title: '名称',
          dataIndex: 'graphicName',
          align: 'center',
          sorter: true,
        },
        {
          title: '用量',
          dataIndex: 'unitAmount',
          align: 'center',
          width: 60,
          sorter: true,
        },
      ];
    },
    //tablelist
    tableList(val) {
      this.tableInfo = val;
    },
    //行选中
    selectChange(val) {
      this.selectedRow=val;
      if (val.length != 0) {
        if(val[0].unitAmount==null||val[0].unitAmount==""){
          this.usage = 0;
        }else{
          this.usage = val[0].unitAmount;
        }

        this.addId = val[0].redianCode;
        console.log(val, '行数据');
        let divList = document.getElementById('myBiaoZhuDiv').getElementsByTagName('div');
        console.log(divList);
        for (let i = 0; i < divList.length; i++) {
          if (divList[i].innerText == val[0].redianCode) {
            divList[i].classList.remove('backCol2');
            divList[i].classList.add('backCol1');
          } else {
            divList[i].classList.remove('backCol1');
            divList[i].classList.add('backCol2');
          }
        }
      }
    },

    //关闭组件
    close() {
      this.$emit('closed', true);
    },

    //新增
    startBiaoZhu() {
      let div = document.getElementById('myBiaoZhuDiv');
      if (this.addId == '') {
        this.$message.error('请先选择配件!');
        return;
      }
      this.newTab = !this.newTab;
      if (this.newTab) {
        div.style.cursor = 'crosshair';
      } else {
        div.style.cursor = '';
      }
    },

    //重置
    chongBiaoZhu() {
      //重置删除的id
      this.delId = undefined;
      //重置选中的table行
      this.$refs.singleTable.setCurrentRow(null);
      //重置新增的状态
      this.newTab = false;
      this.tn = '';
      this.addId = '';
      //重置拖动的状态
      this.dragging = false;
      this.ty = '';
      //重置标号颜色
      let divList = document.getElementById('myBiaoZhuDiv').getElementsByTagName('div');
      for (let i = 0; i < divList.length; i++) {
        divList[i].classList.remove('backCol1');
        divList[i].classList.add('backCol2');
      }
    },

    //删除
    delBiaoZhu() {
      console.log(this.delId, '要删除的坐标id');
      if (this.delId != undefined) {
        this.$confirm('确认要删除此热点吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          //删除元素
          let parentNode = document.getElementById('myBiaoZhuDiv');
          parentNode.removeChild(this.delId);
          // let all=document.getElementById("myBiaoZhuDiv").getElementsByTagName("div")
          // for(let i=0;i<all.length;i++){
          //   if(all[i].id==this.delId){
          //     parentNode.removeChild(all[i]);
          //   }
          // }
          //删除数组里的坐标
          //找到要删除的div的下标
          console.log(this.banMa, '删除前');
          let iList = [];
          for (let i = 0; i < this.banMa.length; i++) {
            if (this.banMa[i].divId == this.delId.id) {
              iList.push(i);
            }
          }
          console.log(iList, 'idList');
          for (let i = 0; i < iList.length; i++) {
            this.banMa.splice(iList[i], 1);
          }
          console.log(this.banMa, '删除后');
          this.delId = undefined;
        });
      }
    },

    move(e) {
      let odiv = e.target; //获取目标元素
      this.selectTable(e);
      //把当前点击标号盒子id存起来
      this.delId = odiv;
      //获取所有的标号
      let divList = document.getElementById('myBiaoZhuDiv').getElementsByTagName('div');
      console.log(divList);
      for (let i = 0; i < divList.length; i++) {
        divList[i].classList.remove('backCol1');
        divList[i].classList.add('backCol2');
      }
      e.target.classList.remove('backCol2');
      e.target.classList.add('backCol1');
      //在数组中找到当前点击的标号的位置
      let indexz;
      for (let i = 0; i < this.banMa.length; i++) {
        if (e.target.id == this.banMa[i].divId) {
          indexz = i;
        }
      }
      //算出鼠标相对元素的位置
      let disX = e.clientX - odiv.offsetLeft;
      let disY = e.clientY - odiv.offsetTop;

      document.onmousemove = (e) => {
        //鼠标按下并移动的事件
        //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        //移动当前元素
        odiv.style.left = left + 'px';
        odiv.style.top = top + 'px';
        //修改存在数组中该标号的坐标位置
        console.log(this.banMa[indexz], '移动后的坐标');
        this.banMa[indexz].gradeX = left + this.pointSize / 2;
        this.banMa[indexz].gradeY = top + this.pointSize / 2;
      };

      document.onmouseup = (e) => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    },

    //点击标号table行选中
    selectTable(e) {
      this.selectedRow=[];
      //this.$refs.singleTable.setCurrentRow(this.tableInfo[e.target.innerText-1]);
      //点击标号
      let redianCode = e.target.getAttribute('redianCode');
      //行选中
      let v;
      let val = this.tableInfo;
      for (let i = 0; i < val.length; i++) {
        if (val[i].redianCode == redianCode) {
          v = i;
          break;
        }
      }
      this.selectedRow = [val[v]];
    },

    //显示标号
    showBiaoZhu(row) {
      console.log(row, '行数据');
      this.currentRow = row;
      let divList = document.getElementById('myBiaoZhuDiv').getElementsByTagName('div');
      console.log(divList);
      for (let i = 0; i < divList.length; i++) {
        if (divList[i].innerText == row.redianCode) {
          divList[i].classList.remove('backCol2');
          divList[i].classList.add('backCol1');
        } else {
          divList[i].classList.remove('backCol1');
          divList[i].classList.add('backCol2');
        }
      }
    },

    //保存热点
    subImport() {
      debugger;
      let list = [];
      for (let i = 0; i < this.banMa.length; i++) {
        let obj = {
          assemblyId: this.banMa[i].assemblyId,
          redianCode: this.banMa[i].redianCode,
          graphicId: this.banMa[i].graphicId,
          gradeX: this.banMa[i].gradeX,
          gradeY: this.banMa[i].gradeY,
        };
        list.push(obj);
      }
      this.loading2 = true;
      console.log(list);
      insertAndUpdate({ assemblyId: this.assemblyId, list: list }).then((response) => {
        console.log(response, '查看返回结果');
        if (response.data) {
          this.$notify.success({ title: '提示信息', message: '保存成功' });
          this.saveLoading = false;
          this.close();
        }
      });
    },

    async getList() {
      await queryGradeInFo({ assemblyId: this.assemblyId }).then((response) => {
        console.log(response.data, '返回结果');
        this.tableData = response.data;
        console.log(this.tableData, '返table');
        for (let i = 0; i < this.tableData.length; i++) {
          this.createMarker(parseInt(this.tableData[i].gradeX), parseInt(this.tableData[i].gradeY), this.tableData[i].redianCode);
        }
      });
    },

    //鼠标按下时触发的方法---标号上的事件
    mousedown(e) {
      e.stopPropagation();
      let odiv = e.target; //获取目标元素
      this.selectTable(e);
      //把当前点击标号盒子id存起来
      this.delId = odiv.id;
      //获取所有的标号
      let divList = document.getElementById('myBiaoZhuDiv').getElementsByTagName('div');
      console.log(divList);
      for (let i = 0; i < divList.length; i++) {
        divList[i].classList.remove('backCol1');
        divList[i].classList.add('backCol2');
      }
      odiv.classList.remove('backCol2');
      odiv.classList.add('backCol1');
      //在数组中找到当前点击的标号的位置
      let indexz;
      for (let i = 0; i < this.banMa.length; i++) {
        if (odiv.id == this.banMa[i].divId) {
          indexz = i;
        }
      }
      console.log(this.banMa[indexz], '移动前的坐标');
      console.log(e.button, '鼠标左键按下了');
      //算出鼠标相对元素的位置
      let disX = e.clientX - odiv.offsetLeft;
      let disY = e.clientY - odiv.offsetTop;
      document.onmousemove = (e) => {
        e.stopPropagation();
        console.log(e.target, '查看e');
        e = e || window.event;
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        odiv.style.left = left + 'px';
        odiv.style.top = top + 'px';
        //修改存在数组中该标号的坐标位置
        this.banMa[indexz].gradeX = left + this.pointSize / 2;
        this.banMa[indexz].gradeY = top + this.pointSize / 2;
        //this.banMa.splice(indexz,1,list)
        console.log(this.banMa[indexz], '移动后的坐标');
        document.onmouseup = (e) => {
          e.stopPropagation();
          console.log(this.banMa[indexz], '放手后的坐标');
          document.onmousemove = null;
          document.onmouseup = null;
        };
      };
    },

    //鼠标松开时触发的方法---标号上的事件
    mouseup(e) {
      console.log('鼠标左键松开了');
    },

    //鼠标按下时触发的方法---图片上的事件
    myBiaoZhuMousedown(e) {
      if (e.button == 0) {
        //判断是否右击
        /*
              event.screenX是屏幕左上角到鼠标当前位置的x轴距离;
              event.clientX是浏览器左上角到鼠标当前位置的x轴距离;
              event.setoffX是鼠标当前点击控件左上角到鼠标当前位置的x轴距离;
              */
        if (this.newTab) {
          //判断要画的热点是否超过用量
          //获取所有的标号
          // let n = 0;
          // let divList = document.getElementById('myBiaoZhuDiv').getElementsByTagName('div');
          // for (let i = 0; i < divList.length; i++) {
          //   if (this.addId == divList[i].innerText) {
          //     n++;
          //   }
          // }
          // if (n == this.usage) {
          //   //说明此热点数量已经达到用量
          //   this.$message.error('编辑热点数量不可超过用量!');
          //   return;
          // }

          //相对当前坐标系的内容区域左上角开始的坐标
          var x = e.offsetX || e.layerX;
          var y = e.offsetY || e.layerY;
          var myImg = document.querySelector('#myBiaoZhu');
          var currWidth = myImg.clientWidth;
          var currHeight = myImg.clientHeight;
          var ProportionWidthInImg = x / currWidth;
          var ProportionHeightInImg = y / currHeight;
          // console.log("图片比例高度："+ProportionHeightInImg)
          // console.log("图片比例宽度："+ProportionWidthInImg)
          this.createMarker(x, y, this.addId);
        }
      }
    },

    //画点
    createMarker(x, y, z) {
      console.log(x, y, z, '创建标号的数据');
      let that = this;
      var div = document.createElement('div');
      div.className = 'marker';
      div.id = 'marker' + this.banMa.length;
      //获取图解总成或备件id
      this.banMa.push({
        divId: div.id,
        assemblyId: this.assemblyId,
        redianCode: z,
        graphicId: this.graphicId,
        gradeX: x,
        gradeY: y,
      });
      console.log(this.banMa, '坐标集合');
      y = y - this.pointSize / 2;
      x = x - this.pointSize / 2;
      div.style.width = '20px';
      div.style.height = '20px';
      div.innerText = z;
      div.style.lineHeight = '20px';
      div.style.color = '#033051';
      div.style.textAlign = 'center';
      div.classList.add('backCol2');
      div.style.borderRadius = '50%';
      div.style.position = 'absolute';
      div.style.left = x + 'px';
      div.style.top = y + 'px';
      div.style.cursor = 'pointer';
      div.setAttribute('redianCode', z);
      document.getElementById('myBiaoZhuDiv').appendChild(div);
      div.addEventListener('mousedown', this.move, false);
      //点击鼠标事件
      div.oncontextmenu = (e) => {
        //阻止冒泡行为和默认右键菜单事件，同时删除该点
        if (e.button == 2) {
          this.$confirm('确认要删除此热点吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            //获取目标元素的id
            var id = e.target.id;
            //找到要删除的div的下标
            console.log(this.banMa, '删除前');
            let iList = [];
            for (let i = 0; i < this.banMa.length; i++) {
              if (this.banMa[i].divId == e.target.id) {
                iList.push(i);
              }
            }
            console.log(iList, 'idList');
            for (let i = 0; i < iList.length; i++) {
              this.banMa.splice(iList[i], 1);
            }
            document.getElementById('myBiaoZhuDiv').removeChild(div);
            console.log(this.banMa, '删除后');
          });
        }
        if (e && e.preventDefault) {
          //阻止默认浏览器动作(W3C)
          e.preventDefault();
        } else {
          //IE中阻止函数器默认动作的方式
          window.event.returnValue = false;
        }
        return false;
      };
    },
  },
};
</script>

<style scoped>
body {
  -moz-user-select: none;
  -khtml-user-select: none;
  user-select: none;
}
.backCol1 {
  background-color: #ea6868;
}
.backCol2 {
  background-color: #36c6d3;
}
/* 用来设置当前页面element全局table 选中某行时的背景色*/
#singleTable tr.current-row > td {
  background-color: #e4e4e4 !important;
  /* color: #f19944; */ /* 设置文字颜色，可以选择不设置 */
}
</style>
